package com.biz.primus.ms.tms.specification;

import com.biz.primus.model.tms.enums.DeliveryOrderStatus;
import com.biz.primus.ms.tms.dao.po.DeliveryOrderPo;
import com.google.common.collect.Lists;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * DeliverOrderListSpecification
 *
 * @author JKLiues
 * @date 2017年11月22日
 */
@Getter
@Setter
public class DeliverOrderListSpecification implements Specification<DeliveryOrderPo> {


    private String empCode;
    private String depotCode;
    private Set<DeliveryOrderStatus> deliveryStatus;

    public void addDeliveryStatus(DeliveryOrderStatus status) {
        if (CollectionUtils.isNotEmpty(deliveryStatus)) {
            deliveryStatus = new HashSet<>();
        }
        if (status == null) {
            return;
        }
        deliveryStatus.add(status);
    }

    @Override
    public Predicate toPredicate(Root<DeliveryOrderPo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        List<Predicate> predicates = Lists.newArrayList();
        if (StringUtils.isNotBlank(empCode)) {
            predicates.add(cb.equal(root.get("deliveryUserNo").as(String.class), empCode));
        }
        if (StringUtils.isNotBlank(depotCode)) {
            predicates.add(cb.equal(root.get("depotCode").as(String.class), depotCode));
        }
        if (CollectionUtils.isNotEmpty(deliveryStatus)) {
            predicates.add(root.get("deliveryStatus").as(DeliveryOrderStatus.class).in(deliveryStatus));
        }
        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    }
}